package com.zyg.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.zyg.common.entity.PayAsyncVo;
import com.zyg.common.entity.TbPayLog;
import com.zyg.common.utils.AlipayTemplate;
import com.zyg.seckill.client.UserClient;
import com.zyg.seckill.dao.TbSeckillOrderMapper;
import com.zyg.seckill.entity.TbSeckillOrder;
import com.zyg.seckill.service.PayService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private TbSeckillOrderMapper orderMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private StringRedisTemplate redisTemplate;


    //功能: 1. 进行验签处理
    @Override
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 60000)
    @Transactional
    public String validSignature(PayAsyncVo vo, Map<String, String> params) {
        try {
            //进行验签处理
            boolean b = AlipaySignature.rsaCheckV1(
                    params,
                    alipayTemplate.getAlipay_public_key(),
                    alipayTemplate.getCharset(),
                    alipayTemplate.getSign_type());
            //根据当前订单号得到登录名
            String username = redisTemplate.opsForValue().get(vo.getOut_trade_no());
            //如果成功，就进行正常的业务逻辑
            if(b){
                //第一部分：修改支付日志
                //根据登录名得到支付日志
                String s = redisTemplate.opsForValue().get("seckill_paylog_" + username);
                TbPayLog payLog = JSON.parseObject(s,TbPayLog.class);
                //修改支付日志中的数据
                payLog.setPayTime(new Date());          // 添加支付时间
                payLog.setTradeState("1");              // 修改订单状态为1，代表已支付
                payLog.setTransactionId(vo.getTrade_no()); // 修改流水号
                userClient.update(payLog);

                //第二部分：修改订单状态
                if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
                    //得到秒杀订单编号
                    String orderId = payLog.getOrderList();
                    //得到订单
                    String orderStr = (String) redisTemplate.boundHashOps("seckillOrder").get(username);
                    TbSeckillOrder seckillOrder = JSON.parseObject(orderStr, TbSeckillOrder.class);
                    //修改订单的属性
                    seckillOrder.setStatus("1");                        //代表己支付
                    seckillOrder.setPayTime(new Date());
                    seckillOrder.setTransactionId(vo.getTrade_no());    //流水号

                    //保存订单到数据库中
                    orderMapper.insert(seckillOrder);
                    //将此订单从redis中删除
                    redisTemplate.boundHashOps("seckillOrder").delete(username);
                    //根据用户id保存的登录名也可以删除了
                    redisTemplate.delete(orderId);
                }
                return "success";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "fail";
    }
}